﻿using Face8280WebSocketServer.Controllers.WebSocket;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Face8280WebSocketServer.Utility.Extend;

namespace Face8280WebSocketServer.Controllers
{
    public class WebSocketServerChannel
    {
        System.Net.WebSockets.WebSocket WebSocketClient;
        string Sn;
        static ConcurrentDictionary<string, WebSocktParamDetail> Results = new ConcurrentDictionary<string, WebSocktParamDetail>();
        static Queue<WebSocktParamDetail> ResultsQueue = new();
        public string CmdResult { get; set; }
        public WebSocketServerChannel(System.Net.WebSockets.WebSocket socket, string sn)
        {
            WebSocketClient = socket;
            Sn = sn;
        }
        public async Task Receive()
        {
            try
            {
                var buffer = new byte[1024 * 4];
                WebSocketReceiveResult result;
                List<byte> data = new();
                int len = 0;
                while (true)
                {
                    result = await WebSocketClient.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
                    if (result.CloseStatus.HasValue) break;
                    data.AddRange(buffer);
                    len += result.Count;
                    if (result.EndOfMessage)
                    {
                        //ResultsQueue.Enqueue(new WebSocktDetail
                        //{
                        //    Data = Encoding.UTF8.GetString(data.ToArray()),
                        //    Channel = this
                        //});
                        len = 0;
                        data.Clear();
                    }
                }
                WebSocketCloseStatus closeStatus = WebSocketCloseStatus.InternalServerError;
                if (result.CloseStatus != null)
                {
                    closeStatus = (WebSocketCloseStatus)result.CloseStatus;
                }
                await WebSocketClient.CloseAsync(closeStatus, result.CloseStatusDescription, CancellationToken.None);
            }
            catch (Exception ex)
            {
                Console.WriteLine("连接发生错误:" + ex.Message);
            }
            Console.WriteLine("连接已断开");
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sn">设备SN</param>
        /// <param name="data">待发送的数据</param>
        /// <param name="isWait">是否等待返回结果</param>
        public string Send(WebSocktParamDetail detail, bool isWait = true)
        {
            var dicData = detail.RequestData.ToJson().ToJObject();
            if (!dicData.ContainsKey("cmd"))
            {
                dicData.Add("cmd", detail.Cmd);
            }
            var buffer = Encoding.UTF8.GetBytes(dicData.ToJson());
            WebSocketClient.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Text, true, CancellationToken.None);
            return CmdResult;
        }


    }
}
